import { existsSync } from 'fs-extra';
import { join, resolve } from 'path';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { getProRootPath } from '../utils';

export function kebabCase (key: string) {
  const result = key.replace(/([A-Z])/g, ' $1').trim();
  return result.split(' ').join('-').toLowerCase();
}

function getSideEffects (partialName: string, compDirName: string) {
  const file = `${compDirName}/${kebabCase(partialName)}/index.sass`;
  if (existsSync(file)) {
    return file;
  }
  return '';
}

function customCompResolver (childDirName = 'common', prefix_name = 'Vc') {
  const compDirName = `vc/src/${childDirName}`;
  return (name: string) => {
    const _name = prefix_name;
    if (name.startsWith(_name)) {
      const partialName = name.slice(_name.length);
      return {
        name: partialName,
        from: compDirName,
        sideEffects: getSideEffects(partialName, compDirName)
      };
    }
  };
}

export function autoComponents (root: string) {
  return Components({
    dirs: [join(getProRootPath(root, 'admin'), 'packages/components/src/web')],
    extensions: ['vue'],
    directoryAsNamespace: true,
    dts: resolve(root, './types/components.d.ts'),
    resolvers: [ElementPlusResolver({
      directives: false
    }), customCompResolver('web')],
    exclude: []
  });
}
